const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const { Course, Category, Chapter, User } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound, BadRequest } = require('http-errors');
/**
 * 查询课程列表
 * GET /web/courses
 */
router.get('/', async (req, res) => {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      order: [['id', 'DESC']],
      where: {},
      limit: pageSize,
      offset: offset,
    };
    if (query.categoryId) {
      if (!(await Category.findByPk(query.categoryId))) {
        throw new BadRequest('获取课程列表失败，分类不存在。');
      }
      condition.where.categoryId = query.categoryId;
    }
    if (query.name) {
      condition.where.name = { [Op.like]: `%${query.name}%` };
    }

    const { count, rows } = await Course.findAndCountAll(condition);
    success(res, '查询课程列表成功。', {
      data: rows,
      total: count,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询课程详情
 * GET /web/courses/:id
 */
router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;
    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId'] },
    };
    const course = await Course.findByPk(id, condition);
    if (!course) {
      throw new NotFound(`ID: ${id}的课程未找到。`);
    }
    const [category, user, chapters] = await Promise.all([
      // 查询课程关联的分类
      await course.getCategory({
        attributes: ['id', 'name'],
      }),
      // 查询课程关联的用户
      await course.getUser({
        attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
      }),

      // 查询课程关联的章节
      await course.getChapters({
        attributes: ['id', 'title', 'rank', 'createdAt'],
        order: [
          ['rank', 'ASC'],
          ['id', 'DESC'],
        ],
      }),
    ]);

    success(res, '查询课程成功。', {
      data: { course, category, user, chapters },
    });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
